<?php

namespace App\Console\Commands;

use App\Component\WeiXin;
use App\Models\IpCrontab;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Ping extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ping:pong';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'ip ping';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        info('commands ping test');
        $failHost = array();
        IpCrontab::query()->with('host')->chunk(100, function ($list) use (&$failHost){
            foreach ($list as $item){
                $host = $item->host->host;
                $port = $item->host->port;
                $transport = 'tcp';
                $timeout   = 0.5;
                // 如果不是IPv4
                if (false === filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                    // 如果是IPv6
                    if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                        $host = '[' . $host . ']';
                    }
                }

                if (starts_with($host,'https')){
                    $host = substr($host,8);
                }elseif (starts_with($host,'http')){
                    $host = substr($host,7);
                }

                try {
                    $host = gethostbyname($host); // 这里如果挂了，说明服务器的DNS解析不给力，必须换
                    if (preg_match('/[A-Za-z]+/',$host)){
                        $check_result = 3;
                        $failHost[$item->open_id][] = $item->host->host.':'.$item->host->port;
                    }else {
                        $fp = @stream_socket_client($transport . '://' . $host . ':' . $port, $errno, $errstr, $timeout);
                        if (!$fp) {
                            $check_result = 2;
                            $failHost[$item->open_id][] = $item->host->host.':'.$item->host->port;
                        } else {
                            $check_result = 1;
                        }
                        @fclose($fp);
                    }
                    IpCrontab::query()->where('id',$item->id)->update(compact('check_result'));
                }
                catch (\Exception $e) {
                    info($e);

                }
            }
        });
        if (!empty($failHost)){
            $Wx = new WeiXin();
            foreach ($failHost as $key => $item){
                $Wx->sendTemplateMessage($key,'TmH10Cq9Is44K99u9fJB8l6LGn8urta3v_saPX_mHH0','pages/index/index',[implode(',',$item),'不可用',date('Y-m-d H:i:s')]);
            }
        }
    }
}
